(function() {

    var $ = ipoevents.jQuery;

    ipoevents.AjaxFormUpload = function() {

        var
        iframe = null,
        uploadForm = null,
        uid = null;

        this.hideElement = function(element) {
            element.css('position', 'absolute');
		    element.css('top', '-1200px');
		    element.css('left', '-1200px');
        };

        this.getIFrameName = function() {
            return uid + '-iframe';
        };

        this.createIFrame = function(callback, callbackContext) {
            if (iframe !== null) return;

            iframe = $('<iframe name="' + this.getIFrameName() + '" src="about:blank"></iframe>');
            this.hideElement(iframe);
            $(document.body).append(iframe);

            var self = this;
            $(iframe).load(function() { callback.call(callbackContext, self); });
        };

        this.createUploadForm = function(action) {
            if (uploadForm !== null) return;

            uploadForm = $('<form target="' + this.getIFrameName() + '" action="' + action + '" '
                + 'method="post" enctype="multipart/form-data"></form>');
            this.hideElement(uploadForm);
            $(document.body).append(uploadForm);
        };

        this.init = function(o) {
            uid = ipoevents.uidGenerator.getUid();
            this.createIFrame(o.callback, o.callbackContext);
            this.createUploadForm(o.formAction);
        };

        this.addFileInput = function(fileInput) {
            var newFileInput = fileInput.clone();
            fileInput.attr('id', uid + '-file-input');
            fileInput.before(newFileInput);
            uploadForm.append(fileInput);

            return newFileInput;
        };

        this.addTextInput = function(name, value) {
            uploadForm.append($('<input type="text" value="' + value + '" name="' + name + '" />'));
        };

        this.submit = function() {
            uploadForm.submit();
        };

        this.destroy = function() {
            if (iframe !== null) iframe.remove();
            if (uploadForm !== null) uploadForm.remove();
        };

        this.getIFrameContent = function() {
            var f = iframe, content = null;

            if (f == null) return content;

            f = f.get(0);

            if (f.contentWindow) {
                content = f.contentWindow.document.body ? f.contentWindow.document.body.innerHTML : null;
            } else if (f.contentDocument) {
                content = f.contentDocument.document.body ? f.contentDocument.document.body.innerHTML : null;
            }

            return content;
        };

    };

})();
